using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace RGB.SharePoint.Util.SPExtendedImageField
{
	public class SPExtendedImageField : SPFieldText
	{

		public SPExtendedImageField(SPFieldCollection fields, string fieldName) : base(fields, fieldName) { }
		public SPExtendedImageField(SPFieldCollection fields, string typeName, string displayName) : base(fields, typeName, displayName) { }

		/// <summary>
		/// Checks the validity of the value
		/// </summary>
		/// <param name="value">Value to check</param>
		/// <returns>The value</returns>
		public override string GetValidatedString(object value)
		{

			// Get the value
			string val = value as string;

			// If the value is null
			if (string.IsNullOrEmpty(val))
			{

				// If the field is required, throws an exception
				if (IsFieldRequired())
					throw new SPFieldValidationException(SPUtility.GetLocalizedString("$Resources:EmptyField", "SPExtendedImageField", SPContext.Current.Web.Language));

				// Return an empty string
				return string.Empty;
			}
			return val;
		}

		/// <summary>
		/// Determine if the field is read only ir not. Fix the bug of the content type.
		/// </summary>
		/// <returns>Wether the field is read only or not</returns>
		private Boolean IsFieldRequired()
		{
			return SPContext.Current.Fields[Id].Required;
		}

		public override BaseFieldControl FieldRenderingControl
		{
			get
			{
				BaseFieldControl fieldControl = new SPExtendedImageFieldControl(this) { FieldName = InternalName };
				return fieldControl;
			}
		}

	}

}
